﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByteSite.Common
{
    public class ImageHelper
    {
        public static void Base64ToImage(string base64, string path)
        {
            if (!string.IsNullOrEmpty(base64) && !string.IsNullOrEmpty(path))
            {
                if (base64.StartsWith("data:image"))
                {
                    string[] strBase64 = base64.Split(',');
                    string encodedImage = strBase64[1];
                    string dummyData = encodedImage.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
                    if (dummyData.Length % 4 > 0)
                    {
                        dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                    }

                    byte[] bt = Convert.FromBase64String(dummyData);
                    System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);
                    Bitmap bitmap = new Bitmap(stream);
                    bitmap.Save(path);
                }
            }
        }

        public static string ImageToBase64(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                Image image = Image.FromFile(path);
                if (image != null)
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        image.Save(memoryStream, image.RawFormat);
                        byte[] imageBytes = memoryStream.ToArray();
                        return Convert.ToBase64String(imageBytes);
                    }
                }
            }
            return "";
        }

        public string GetImageExt(Image image)
        {
            string imageExt = "";
            var RawFormatGuid = image.RawFormat.Guid;
            if (ImageFormat.Png.Guid == RawFormatGuid)
            {
                imageExt = "png";
            }
            if (ImageFormat.Jpeg.Guid == RawFormatGuid)
            {
                imageExt = "jpg";
            }
            if (ImageFormat.Bmp.Guid == RawFormatGuid)
            {
                imageExt = "bmp";
            }
            if (ImageFormat.Gif.Guid == RawFormatGuid)
            {
                imageExt = "gif";
            }
            if (ImageFormat.Icon.Guid == RawFormatGuid)
            {
                imageExt = "icon";
            }
            return imageExt;
        }
    }
}
